package com.spc.car.data.util;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.objenesis.instantiator.util.ClassUtils;

public final class BeanUtil {
    private BeanUtil() {
    }

    public static Map<String, Object> beanToMap(Object bean) {
        return null == bean ? null : BeanMap.create(bean);
    }

    public static <T> T mapToBean(Map<String, Object> map, Class<T> clazz) {
        T bean = ClassUtils.newInstance(clazz);
        BeanMap.create(bean).putAll(map);
        return bean;
    }

    public static <T> List<Map<String, Object>> beansToMaps(List<T> beans) {
        return CollectionUtils.isEmpty(beans) ? Collections.emptyList() : (List)beans.stream().map(BeanUtil::beanToMap).collect(Collectors.toList());
    }

    public static <T> List<T> mapsToBeans(List<Map<String, Object>> maps, Class<T> clazz) {
        return CollectionUtils.isEmpty(maps) ? Collections.emptyList() : (List)maps.stream().map((e) -> {
            return mapToBean(e, clazz);
        }).collect(Collectors.toList());
    }
}
